package com.wva.user.strategy.impl;

import com.wva.common.client.CaptchaClient;
import com.wva.common.domain.dto.SmsCaptchaVerifyDTO;
import com.wva.common.exception.BusinessException;
import com.wva.common.exception.SystemException;
import com.wva.common.status.StatusEnum;
import com.wva.common.utils.R;
import com.wva.common.utils.RandomUtils;
import com.wva.redis.utils.RedisUtils;
import com.wva.user.domain.dto.LoginDTO;
import com.wva.user.domain.po.User;
import com.wva.user.enums.LoginType;
import com.wva.user.service.UserService;
import com.wva.user.strategy.AbstractLoginStrategy;
import com.wva.user.utils.LoginUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SmsLoginStrategy extends AbstractLoginStrategy {
    @Autowired
    UserService userService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    CaptchaClient captchaClient;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    LoginUtils loginUtils;

    @Override
    public String login(LoginDTO loginDTO) {
        //校验短信验证码
        SmsCaptchaVerifyDTO smsCaptchaVerifyDTO = new SmsCaptchaVerifyDTO();
        BeanUtils.copyProperties(loginDTO, smsCaptchaVerifyDTO);
        R<Object> result = captchaClient.verifySmsCaptcha(smsCaptchaVerifyDTO);
        if (result.getCode() != 0) {
            throw new BusinessException(result);
        }

        //判断是否注册过
        User user = userService.lambdaQuery()
                .eq(User::getPhoneNumber, loginDTO.getPhone())
                .one();

        //用户不存在
        if (user == null) {
            //还没注册过，新建一个账号！
            User newUser = new User();
            String nickname = "用户"+ RandomUtils.getRandomId().substring(0, 10);
            newUser.setNickname(nickname);
            newUser.setPhoneNumber(loginDTO.getPhone());
            boolean success = userService.save(newUser);
            if (!success) {
                log.error("短信登录注册方式插入新用户记录失败");
                throw new SystemException(StatusEnum.INTERNAL_ERROR);
            }
            return loginUtils.getTokenByUserId(newUser.getId());
        } else if (user.getDelFlag() == 1) {
            //TODO 用户存在但是已注销
            //删除已有用户
            //插入新用户
            throw new BusinessException("用户已注销");
        } else {
            //用户已存在且非注销状态
            return loginUtils.getTokenByUserId(user.getId());
        }
    }

    @Override
    protected LoginType getLoginType() {
        return LoginType.SMS;
    }

    @Override
    public Class<?> getGroup() {
        return LoginDTO.Sms.class;
    }
}
